#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>

void Useage(const std::string& s)
{
    std::cout << "Useage" << ":\n\t" << " ip port\n";
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Useage(argv[0]);
        exit(0);
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    int socketfd = socket(AF_INET, SOCK_STREAM, 0);
    if(socketfd < 0)
    {
        std::cerr << "socket error\n";
        exit(1);
    }

    struct sockaddr_in peer;
    memset(&peer, 0, sizeof peer);
    peer.sin_family = AF_INET;
    peer.sin_port = htons(port);
    peer.sin_addr.s_addr = inet_addr(ip.c_str());

    int n = connect(socketfd, (const sockaddr*)&peer, sizeof peer);
    if(n < 0)
    {
        std::cerr << "connect fail\n";
        exit(2);
    }

    while(true)
    {
        std::string message;
        std::cout << "Please input #";
        std::getline(std::cin, message);
        send(socketfd, message.c_str(), message.size(), 0);

        char inbuff[1024];
        int n = recv(socketfd, inbuff, sizeof(inbuff) - 1, 0);
        if(n > 0)
        {
            inbuff[n] = '\0';
            std::cout << inbuff << std::endl;
        }
        else 
        {
            std::cout << "server closed\n";
            break;
        }


    }

    return 0;
}